package cn.kust.apiuser.interceptor;

import cn.kust.microtourismcommon.constant.TokenConstants;
import cn.kust.microtourismcommon.pojo.dto.ResponseResult;
import cn.kust.microtourismcommon.pojo.dto.TokenResult;
import cn.kust.microtourismcommon.util.JwtUtils;
import cn.kust.microtourismcommon.util.RedisPrefixUtils;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @author WY
 * @data 2022/7/21 10:17
 **/
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       //设置响应头的编码：
        response.setHeader("content-type","text/html;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");


        boolean result = Boolean.TRUE;
        String resultString = "";
        String token = request.getHeader("Authorization");

        // 请求头中的token
        TokenResult tokenResult = JwtUtils.checkToken(token);
        //验证token
        if (tokenResult == null) {
            resultString = "token invalid";
            result = false;
        } else {
//            将客户端的内容进行对比
            String phone = tokenResult.getPhone();
            String identity = tokenResult.getIdentity();
            String tokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);
            String tokenRedis = stringRedisTemplate.opsForValue().get(tokenKey);
            //如果redis中没有获取到对应的token，或者获取到的与客户端发送来的不一致
            if ((!StringUtils.hasLength(tokenRedis)) || !token.trim().equals(tokenRedis.trim())) {
                resultString = "access token失效，请刷新token ";
                result = false;
            }
        }

        //比较是否相等
        if (!result){

            PrintWriter pw = response.getWriter();
            pw.print(JSONObject.toJSON(ResponseResult.fail(resultString)));
        }

        return result;
    }
}
